package org.nobject.common.lang;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Set;

import org.nobject.common.buffer.ByteBuffer;


/**
 * IO工具类
 *
 * @author bianrongjun
 * @version 1.0
 */
public class IOUtils {
	
	/** 
	 * 获取输入流字符串
	 * @param is 输入流
	 * @return 文件内容
	 */
	public static String getString(InputStream is){
		return getString(is,"UTF-8",1024);
	}

	/** 
	 * 获取输入流字符串
	 * @param is 输入流
	 * @param charset 字符集
	 * @param partSize 流块大小
	 */
	public static String getString(InputStream is,String charset) {
		return getString(is,charset,1024);
	}
	
	/** 
	 * 获取输入流字符串
	 * @param is 输入流
	 * @param charset 字符集
	 * @param partSize 流块大小
	 */
	public static String getString(InputStream is,String charset,int partSize) {
		InputStreamReader isr;
		try {
			isr = new InputStreamReader(is, charset);
			char data[] = new char[partSize];
			StringBuffer sb = new StringBuffer();
			int i = 0;
			while ((i = isr.read(data)) > 0) sb.append(data, 0, i);
			return sb.toString();
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
		
	}
	
	/** 
	 * 获取输入流字节数组
	 * @param is 输入流
	 */
	public static byte[] getBytes(InputStream is) throws IOException {
		byte data[] = new byte[1024];
		ByteBuffer sb = new ByteBuffer();
		int i = 0;
		while ((i = is.read(data)) > 0){
			sb.append(data, 0, i);
		}
		return sb.getBytes();
	}
	
	/**
	 * 获取输入流<br>
	 * @param path 路径
	 */
	public static InputStream getInputStreamByFilepath(String path) {
		try {
			return new FileInputStream(new File(path));
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

	/**
	 * 获取输入流<br>
	 * @param classpath 类路径
	 */
	public static InputStream getInputStreamByClasspath(String classpath) {
		
		Set<ClassLoader> loaders=ClassUtils.getClassLoaders();
		for(ClassLoader loader:loaders){
			InputStream is=loader.getResourceAsStream(classpath);
			if(is==null) continue;
			return is;
		}
		throw new RuntimeException("未找到资源:"+classpath);
		
		//return IOUtils.class.getClassLoader().getResourceAsStream(ClassUtils.removePreClasspath(classpath));
	}
	
	/**
	 * @param path
	 * @return
	 */
	public static byte [] getStreamBytesByPath(String path){
		path=ClassUtils.removePreClasspath(path);
		while(path.startsWith(File.separator)){
			path=path.substring(1);
		}
		InputStream is=ClassLoader.getSystemClassLoader().getResourceAsStream(path);
		if(is==null) return null;
		try {
			ByteBuffer bb=new ByteBuffer();
			byte []b=new byte [1024];
			int c=0;
			while((c=is.read(b))>0){
				bb.append(b, 0, c);
			}
			return bb.getBytes();
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
		
	}
}
